package jk.spider.core.storage.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import jk.spider.core.storage.FolderDAO;
import jk.spider.model.Folder;

import org.apache.log4j.Logger;

public class FolderDAOImpl implements FolderDAO {
	protected static final Logger log = Logger.getLogger(FolderDAOImpl.class);
	protected DAOHelp daoHelp;
	public FolderDAOImpl(DAOHelp daoHelp) {
		this.daoHelp = daoHelp;
	}
	public Folder findById(int rid) {
		Folder folder = null;
		Statement stmt = null;
		String sql = "select * from spider_folder where rid = " + rid;
		ResultSet rs = null;
		try {
			stmt = daoHelp.getConnection().createStatement();
			rs = stmt.executeQuery(sql);
			while (rs.next()) {
				folder = this.createFolderFromRecord(rs);
			}
			daoHelp.safeClose(rs);
			daoHelp.safeClose(stmt);
		} catch (SQLException e) {
			log.error("SQLException -> ", e);
			daoHelp.safeClose(rs);
			daoHelp.safeClose(stmt);
		} finally {
			daoHelp.safeClose(rs);
			daoHelp.safeClose(stmt);
		}
		
		return folder;
		
	}

	public void createFolder(Folder folder) {
		String sql = "insert into spider_folder (rid,fname,ftype) values ("+ daoHelp.format(folder.getRid()) + "," +
				 " " + daoHelp.format(folder.getFName()) + "," + daoHelp.format(folder.getFType())  + ")" ;
		daoHelp.execSql(sql);
	}
	
	public void deleteAll() {
		String sql = "delete from spider_folder";
		daoHelp.execSql(sql);
	}
	
	protected Folder createFolderFromRecord(ResultSet rs)  {
		try {
			String fName = rs.getString("fName");
			String fType = rs.getString("fType");
			
			Folder folder = new Folder();
			folder.setFName(fName);
			folder.setFType(fType);
			return folder;
		} catch (SQLException e) {
			return null;
		}
	}
}
